/*  File Name	: SandBoxService.cpp
 *  Author		: Javie Pong
 *	 E-mail		: 823960168@qq.com
 *  Created on	: 2012-10-31
 *  Description:
 */

#include "SandBoxService.h"
#include "SandBoxMonitor.h"

SandBoxService::SandBoxService(int p)
{

}

SandBoxService::~SandBoxService()
{

}


int SandBoxService::open(void *p)
{
	if(this->monitor()->bind_service(this)<0)
	{
		return -1;
	}
	if(super::open(this->reactor())<0)
	{
		return -1;
	}
	//this->peer()->enable(O_NONBLOCK);
	if(this->start_timer(TimeValue(1),TimeValue(3))<0)
	{
		LOG((ERROR_LOG,"SandBoxService::open-->start_timer error,[ip:%s][port:%d]",
				this->conn_addr_,this->port_));
		return -1;
	}

	LOG((DEBUG_LOG,"SandBoxService::open-->[%s:%d]",this->conn_addr_,this->port_));
	return 0;
}

int SandBoxService::handle_input(int  fd)
{
	this->last_recv_msg_ = TimeValue::now_time_in_sec();
	return	this->recv_msg();
}

int SandBoxService::handle_output(int fd)
{
	return 0;
}

int SandBoxService::handle_timeout(void)
{
	int fd = this->peer()->get_handle();
	if(TimeValue::now_time_in_sec()-this->last_recv_msg_>60*2)
	{
		LOG((DEBUG_LOG,"SandBoxService::handle_timeout-->[fd:%d][%s:%d] session timeout",
				fd,this->conn_addr_,this->port_));
		this->reactor()->remove_handler(fd,this);
	}
	return 0;
}

int SandBoxService::handle_close(int handle,ReactorMask mask)
{
	this->stop_timer();
	super::handle_close();
	return this->monitor()->handle_close(this);
}

int SandBoxService::recv_msg(const int limit_size)
{
	MessageBlock *mb = NULL;
	if (this->monitor()->msg_pool()->pop(mb) != 0)
	{
		LOG((ERROR_LOG,"SandBoxService::recv_msg-1->pop error"));
		return -1;
	}

	int len = 0;
	//bool has_data = false;
	//do
	//{
	mb->reset();
	len = super::recv_msg(mb, mb->size());
	if (len == -1 && (errno == EWOULDBLOCK || errno == EINTR))
	{
		this->monitor()->msg_pool()->push(mb);
		return 0;
	}
	else if (len <= 0)
	{
		LOG((DEBUG_LOG,"SandBoxService::recv_msg-->recv:[%d],error:[%d:%s]",
				len,errno,strerror(errno)));
		this->monitor()->msg_pool()->push(mb);
		return -1;
	}

	//flash sandbox
	static const char szFlashSocketVerify[] = "<policy-file-request/>";
	static const char szFlashSocketVerifyReply[] =
			"<?xml version=\"1.0\"?><cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\"/></cross-domain-policy>\0";

	LOG((DEBUG_LOG,"SandBoxService::recv_msg-->[%d][%d][%s]",mb->data_len(),
			sizeof(szFlashSocketVerify),mb->rd_ptr()));

	if (mb->data_len() == sizeof(szFlashSocketVerify) && 0== strncmp(szFlashSocketVerify, mb->rd_ptr(),
							sizeof(szFlashSocketVerify)))
	{
		mb->reset();
		mb->write(szFlashSocketVerifyReply, sizeof(szFlashSocketVerifyReply));
		this->send_msg(mb, mb->data_len());
		this->monitor()->msg_pool()->pop(mb);
		return 0;
	}
	this->monitor()->msg_pool()->pop(mb);
	return -1;

	//}while (len > 0);

}

void SandBoxService::reset(void)
{

}
